package com.xysq.activity;
/**
 * Copyright (c) 2015 XiaoYuanShenQi. All rights reserved.
 * update by huangdongkai 2015/7/22
 */

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.rockcent.action.CallbackListener;
import com.rockcent.model.CustomerBO;
import com.rockcent.model.SchoolModel;
import com.umeng.analytics.MobclickAgent;
import com.xysq.lemon.R;
import com.xysq.util.ToastUtil;
import com.xysq.util.UserInfoKeeper;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.InjectView;

public class LoginActivity extends BaseActivity implements OnClickListener {
    @InjectView(R.id.ibtn_back)
    ImageButton backIbtn;
    @InjectView(R.id.btn_login)
    Button loginBtn;
    @InjectView(R.id.layout_login)
    LinearLayout loginLayout;
    @InjectView(R.id.btn_to_register)
    Button toRegiterBtn;
    /*    @InjectView(R.id.spinner_schools)
        Spinner schoolsSpinner;*/
    @InjectView(R.id.layout_register)
    LinearLayout registerLayout;
    /*    @InjectView(R.id.layout_login_other)
        LinearLayout loginOtherLayout;*/
    @InjectView(R.id.btn_hide)
    ImageButton hideBtn;
    @InjectView(R.id.txt_login_hide)
    TextView loginHideTxt;
    @InjectView(R.id.edt_login_phone)
    EditText loginPhoneEdt;
    @InjectView(R.id.edt_login_password)
    EditText loginPasswordEdt;
    @InjectView(R.id.edt_register_phone)
    EditText registerPhoneEdt;
    @InjectView(R.id.edt_register_password)
    EditText registerPasswordEdt;
    @InjectView(R.id.edt_register_get_code)
    EditText registerGetCodeEdt;
    @InjectView(R.id.btn_get_identifying_code)
    Button getIndentifyingCodeBtn;
    @InjectView(R.id.btn_register)
    Button registerBtn;
    @InjectView(R.id.img_logo)
    ImageView logoImg;
    @InjectView(R.id.txt_agreement)
    TextView agreementTxt;
    @InjectView(R.id.txt_school)
    TextView schoolTxt;
    @InjectView(R.id.iv_down)
    ImageView downIv;
    @InjectView(R.id.txt_school_id)
    TextView schoolIdTxt;

    private String schoolName;
    private int schoolId;
    private int time = 1000;
    private String loginPhoneNumber;
    private String loginPassword;
    private String registerPhoneNumber;
    private String registerPassword;
    private ArrayAdapter<String> spinSchoolsAdapter;
    private String[] schools;
    private int[] schoolIds;
    private int getCodeTime;
    private Timer mTimer;
    private TimeTask mTask;
    private String code;
    private int schoolsId;
    private boolean isReg = false;
    public static final int RESULT_CODE = 1;
    private boolean isMain = false;//true是否从首页跳转过来
    public final static String IS_MAIN = "isMain";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initView();
        getData();
    }

    private void getData() {
        getSchools();
    }

    private void initView() {
        isMain = getIntent().getBooleanExtra(IS_MAIN,false);
        mTimer = new Timer();
        loginBtn.setOnClickListener(this);
        toRegiterBtn.setOnClickListener(this);
        hideBtn.setOnClickListener(this);
        loginHideTxt.setOnClickListener(this);
        backIbtn.setOnClickListener(this);
        getIndentifyingCodeBtn.setOnClickListener(this);
        registerBtn.setOnClickListener(this);
        agreementTxt.setOnClickListener(this);
        schoolTxt.setOnClickListener(this);
        downIv.setOnClickListener(this);
        loginPhoneEdt.addTextChangedListener(new MyTextWatcher(loginPhoneEdt));
        loginPasswordEdt.addTextChangedListener(new MyTextWatcher(loginPasswordEdt));
        registerPasswordEdt.addTextChangedListener(new MyTextWatcher(registerPasswordEdt));
        registerPhoneEdt.addTextChangedListener(new MyTextWatcher(registerPhoneEdt));

        loginPhoneEdt.setText(UserInfoKeeper.readLoginPhone(this));
        loginPasswordEdt.setText(UserInfoKeeper.readLoginPass(this));
        registerPasswordEdt.setText(UserInfoKeeper.readRegPass(this));
        registerPhoneEdt.setText(UserInfoKeeper.readRegPhone(this));
    }

    @Override
    public void onClick(View view) {
        if (view == toRegiterBtn) {
            MobclickAgent.onEvent(this, "1002");
            showRegister();
            registerPhoneEdt.requestFocus();
            loginHideTxt.setVisibility(View.VISIBLE);
        }
        if (view == hideBtn || view == loginHideTxt) {
            hideRegister();
            loginPhoneEdt.requestFocus();
            loginHideTxt.setVisibility(View.GONE);
        }
        if (view == backIbtn) {
            finish();
        }
        if (view == getIndentifyingCodeBtn) {
            checkExistUser();
        }
        if (view == loginBtn) {
            login();
            MobclickAgent.onEvent(this, "1001");
        }
        if (view == registerBtn) {
            register();
            MobclickAgent.onEvent(this, "1004");
        }
        if (view == agreementTxt) {
            Intent intent = new Intent(this, AgreementActivity.class);
            intent.putExtra(AgreementActivity.URL, "http://www.xyooyo.com/agreement.html");
            startActivity(intent);
        }
        if (view == schoolTxt || view == downIv) {
            Intent intent = new Intent(this, WheelViewActivity.class);
            intent.putExtra(WheelViewActivity.DATAS, schools);
            intent.putExtra(WheelViewActivity.IDS, schoolIds);
            intent.putExtra(WheelViewActivity.FLAG, UserActivity.flagSchool);
            startActivityForResult(intent, WheelViewActivity.CODE);
        }
    }

    public void toGetBackPassword(View view) {
        Intent intent = new Intent(this, GetBackPasswordActivity.class);
        MobclickAgent.onEvent(this, "1003");
        startActivity(intent);
    }

    //检查用户是否存在
    private void checkExistUser() {
        appAction.checkCustExist(registerPhoneEdt.getText().toString(), new CallbackListener<CustomerBO>() {
            @Override
            public void onSuccess(CustomerBO data) {
                if (data == null) {
                    sendSMS();
                } else {
                    ToastUtil.showShort(LoginActivity.this, getResources().getString(R.string.toast_exsit_user));
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(LoginActivity.this, message);
            }
        });
    }

    private void sendSMS() {
        registerPhoneNumber = registerPhoneEdt.getText().toString();
        appAction.sendSmsCode(registerPhoneNumber, new CallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
              /*  appAction.getSmsCode4Register(registerPhoneNumber, new CallbackListener<String>() {
                    @Override
                    public void onSuccess(String data) {
                        if (data == null) {
                            return;
                        } else {
                            registerGetCodeEdt.setText(data);//for testing
                        }
                    }

                    @Override
                    public void onFailure(String errorEvent, String message) {
                    }
                });*/
                ToastUtil.showShort(LoginActivity.this, getResources().getString(R.string.toast_send_sms_success));
                getCodeTime = 60;
                mTask = new TimeTask();
                mTimer.schedule(mTask, 0, 1000);
                getIndentifyingCodeBtn.setEnabled(false);
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtil.showShort(LoginActivity.this, message);
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }
        });
    }

    class TimeTask extends TimerTask {
        @Override
        public void run() {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (getCodeTime < 1) {
                        getIndentifyingCodeBtn.setEnabled(true);
                        getIndentifyingCodeBtn.setText(getResources().getString(R.string.txt_get_code));
                        if (mTask != null) {
                            mTask.cancel();
                        }
                    } else {
                        getIndentifyingCodeBtn.setText("" + getCodeTime);
                    }
                    getCodeTime--;
                }
            });
        }
    }

    private void showRegister() {
        registerLayout.setVisibility(View.VISIBLE);
//        loginOtherLayout.animate().setDuration(time).translationY(-1000).alpha(0).start();
//        loginLayout.animate().setDuration(time).translationY(-50).start();
        ObjectAnimator.ofFloat(registerLayout, "translationY", 1500, 0).setDuration(time / 2).start();
//        registerLayout.animate().setDuration(time).translationYBy(300).translationY(-150).alpha(1).start();
    }

    private void hideRegister() {
//        loginOtherLayout.animate().setDuration(time).translationY(0).alpha(1).start();

//        loginLayout.animate().setDuration(time).translationY(0).start();
/*        registerLayout.animate().setDuration(time).translationY(0).alpha(0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animator) {
                registerLayout.setVisibility(View.INVISIBLE);
                registerLayout.animate().setListener(null);
            }
        }).start();     */
        ObjectAnimator.ofFloat(registerLayout, "translationY", 0, 1500).setDuration(time / 2).start();
    }

    private void getSchools() {
        appAction.getSchool(new CallbackListener<List<SchoolModel>>() {
            @Override
            public void onSuccess(List<SchoolModel> data) {
                if (data == null) {
                    return;
                } else {
                    int size = data.size();
                    schools = new String[size];
                    schoolIds = new int[size];
                    for (int i = 0; i < size; i++) {
                        schools[i] = data.get(i).getName();
                        schoolIds[i] = data.get(i).getUuid();
                    }
//                    spinSchoolsAdapter = new ArrayAdapter<>(LoginActivity.this, android.R.layout.simple_spinner_dropdown_item, schools);
//                    schoolsSpinner.setAdapter(spinSchoolsAdapter);
                }
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtil.showShort(LoginActivity.this, message);
            }
        });
    }

    private void login() {
        loginPhoneNumber = loginPhoneEdt.getText().toString();
        loginPassword = loginPasswordEdt.getText().toString();
        appAction.loginByApp(loginPhoneNumber, loginPassword, new CallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
                ToastUtil.showShort(LoginActivity.this, getResources().getString(R.string.toast_login_successful));
                UserInfoKeeper.writePhoneNumber(LoginActivity.this, loginPhoneNumber);
                writeUuid(loginPhoneNumber);
//                setResult(RESULT_CODE, null);
//                finish();
                if(isMain) {
                    Intent intent = new Intent(LoginActivity.this, MainTabActivity.class);
                    intent.putExtra(MainTabActivity.INDEX, MainTabActivity.TAG_USER);
                    startActivityForResult(intent, RESULT_CODE);
                } else {
                    finish();
                }
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtil.showShort(LoginActivity.this, message);
            }
        });
    }

    //注册
    private void register() {
        registerPhoneNumber = registerPhoneEdt.getText().toString();
        registerPassword = registerPasswordEdt.getText().toString();
        code = registerGetCodeEdt.getText().toString();
        if (TextUtils.isEmpty(schoolIdTxt.getText().toString())) {
            ToastUtil.showShort(this, getResources().getString(R.string.toast_please_choice_school));
            return;
        }
        schoolId = Integer.parseInt(schoolIdTxt.getText().toString());
//        schoolsId = schoolIds[schoolsSpinner.getSelectedItemPosition()];
        appAction.registerByPhone(registerPhoneNumber, code, schoolId, registerPassword, new CallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
/*                Intent intent = new Intent(LoginActivity.this, MainTabActivity.class);
                startActivity(intent);*/
//                UserInfoKeeper.writePhoneNumber(LoginActivity.this, registerPhoneNumber);
                isReg = true;
                //TODO
                UserInfoKeeper.writePhoneNumber(LoginActivity.this, loginPhoneNumber);
                writeUuid(registerPhoneNumber);
//                UserInfoKeeper.writeCustomerId(LoginActivity.this, );
                //登录成功，设置默认支付密码为123456
//                finish();
            }

            @Override
            public void onFailure(String errorEvent, String message) {
                ToastUtil.showShort(LoginActivity.this, message);
            }
        });
    }

    private void writeUuid(final String registerPhoneNumber) {
        appAction.getCustomer(registerPhoneNumber, "", "", new CallbackListener<CustomerBO>() {
            @Override
            public void onSuccess(CustomerBO data) {
                UserInfoKeeper.writeCustomerId(LoginActivity.this, data.getUuid());
                UserInfoKeeper.writePhoneNumber(LoginActivity.this, data.getPhone());
                UserInfoKeeper.writeRealName(LoginActivity.this, data.getName());
                UserInfoKeeper.writeKcouponId(LoginActivity.this, String.valueOf(data.getKcouponId()));
                if (isReg) {
                    initPayPass(registerPhoneNumber, registerPassword);
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                Log.e("+++my uuid", "get uuid failed" + message);
            }
        });
    }

    //设置支付密码为123456
    private void initPayPass(final String loginPhoneNumber, String loginPassword) {
        appAction.initPayPass(loginPhoneNumber, loginPassword, payPass, new CallbackListener<Void>() {
            @Override
            public void onSuccess(Void data) {
                ToastUtil.showShort(LoginActivity.this, R.string.toast_register_successful);
                setResult(RESULT_CODE, null);
//                finish();
                if(isMain) {
                    Intent intent = new Intent(LoginActivity.this, MainTabActivity.class);
                    intent.putExtra(MainTabActivity.INDEX, MainTabActivity.TAG_USER);
                    startActivityForResult(intent, RESULT_CODE);
                } else {
                    finish();
                }
            }

            @Override
            public void onFailure(String errorCode, String message) {
                ToastUtil.showShort(LoginActivity.this, message);
                Log.d("test", message);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("登录页");
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("登录页");
        MobclickAgent.onPause(this);
    }

    private class MyTextWatcher implements TextWatcher {
        private EditText mEditText;

        public MyTextWatcher(EditText e) {
            mEditText = e;
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        public void afterTextChanged(Editable s) {
            switch (mEditText.getId()) {
                case R.id.edt_login_phone:
                    UserInfoKeeper.writeLoginPhone(LoginActivity.this, mEditText.getText().toString());
                    break;
                case R.id.edt_login_password:
                    UserInfoKeeper.writeLoginPass(LoginActivity.this, mEditText.getText().toString());
                    break;
                case R.id.edt_register_phone:
                    UserInfoKeeper.writeRegPhone(LoginActivity.this, mEditText.getText().toString());
                    break;
                case R.id.edt_register_password:
                    UserInfoKeeper.writeRegPass(LoginActivity.this, mEditText.getText().toString());
                    break;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case WheelViewActivity.CODE:
                if (data != null) {
                    Bundle b = data.getExtras();
                    schoolName = b.getString(WheelViewActivity.NAME);
                    schoolId = b.getInt(WheelViewActivity.ID);
                    schoolTxt.setText(schoolName);
                    schoolIdTxt.setText(String.valueOf(schoolId));
                }
                break;
        }
    }
}
